package servlet;

import java.io.FileNotFoundException;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.soap.util.mime.ByteArrayDataSource;
import org.springframework.util.FileCopyUtils;

import com.yahoo.search.ImageSearchRequest;
import com.yahoo.search.ImageSearchResults;
import com.yahoo.search.SearchClient;
import com.yahoo.search.SearchException;

/**
 * @web.servlet name="imageServlet"
 * @web.servlet-mapping url-pattern="/auth/dynmaicImages/*"
 * @author isaac
 *
 */
public class ImageServlet extends HttpServlet{
	private static final long serialVersionUID = 1L;

	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		String artist = request.getPathInfo().substring(1, request.getPathInfo().lastIndexOf('.'));
		
		URLConnection connection = null;
		ImageSearchResults isr = null;
		String imageURL = null;
		
		try {
			SearchClient client = new SearchClient("solesonic.com");
			ImageSearchRequest imageSearch = new ImageSearchRequest(artist);
			imageSearch.setResults(1);
			isr = client.imageSearch(imageSearch);
			
			if(isr.listResults().length > 0) {
				imageURL = isr.listResults()[0].getClickUrl();
			}
		} 
		catch (IOException e1) {} 
		catch (SearchException e1) {}
		
		byte[] artistImage = null;

		if(imageURL != "") {
			URL imgURL;
			try {
				imgURL = new URL(imageURL);
				connection = imgURL.openConnection();
				connection.setRequestProperty("User-agent","Mozilla/4.0");
				ByteArrayDataSource bads = new ByteArrayDataSource(connection.getInputStream(), null);			
				artistImage = bads.toByteArray();
			} 
			catch (MalformedURLException e) {}
			catch (FileNotFoundException e) {}
			catch (IOException e) {}
					
		}
		
		if(artistImage == null) {
			String requestURL = request.getRequestURL().toString();
			String path = request.getContextPath();
			String base = requestURL.substring(0, requestURL.indexOf(path)+path.length());
			
			URL imgURL = new URL(base+"/images/image-not-available.jpg");
			connection = imgURL.openConnection();
			ByteArrayDataSource bads = new ByteArrayDataSource(connection.getInputStream(), null);			
			artistImage = bads.toByteArray();
		}
    	
    	if(artistImage != null) {
	    	response.setContentLength(artistImage.length);
	    	FileCopyUtils.copy(artistImage , response.getOutputStream());
    	}
	}
}